<?php
//公用的静态函数
	define('BASEDIR',str_replace('protected'.DS.'components' ,'' ,dirname(__FILE__)));
class  NC{
	public static function dbg($data,$flag = false){
		echo '<pre>';
		print_r($data);
		if(!$flag)exit;
	}


/*******global functions ********************/

//用户分组
	/*
	define('GUEST' , 1);
	define('EDITOR' , 4);
	define('ADMIN' , 9);
	define('SUPERADMIN' , 18);
	*/

	//星星函数，通过分数直接得到星星代码
	public static function get_statics(){
		return false;
		return 'http://statics.dadipedia.com';
	}
	public static function getUserIcon($uid){
		if(trim($uid) == null)return '/icon/0/0/0';
		$dir1 = floor(intval($uid)/1000000);
		$dir2 = floor(intval($uid)/1000);
		$basedir = dirname(__FILE__);
		$file = BASEDIR . "public/icon/".$dir1.'/'.$dir2.'/'.$uid;
		if(!is_file($file)){
			$path = "/images/default_p.jpg";
		}else{
			$path = "/icon/".$dir1.'/'.$dir2.'/'.$uid;
		}
		$prefix = self::get_header();
		//$prefix = "http://statics.dadipedia.com";
		return $prefix . $path;
	}
	public static function get_icon($uid){
		if(trim($uid) == null)return DS.'icon'.DS.'0'.DS.'0'.DS.'0';
		$dir1 = floor(intval($uid)/1000000);
		$dir2 = floor(intval($uid)/1000);
		return "icon".DS.$dir1.DS.$dir2.DS.$uid;
	}
	public static function defaultPic($picPath){
		if(!$picPath)return '/images/default.jpg';
		//if(!is_file($picPath))return '/images/default.jpg';
		return $picPath;
	}
	public static function get_header(){
		$host = 'http://'.$_SERVER['HTTP_HOST'];
		$host = str_replace("localhost","127.0.0.1",$host);
		return $host;
	}
	public static function _g($para,$return = false){
		if(array_key_exists($para,$_GET)){
			return $_GET[$para];
		}else{
			return $return;
		}
	}
	public static function _p($para,$return = false){
		if(array_key_exists($para,$_POST)){
			return $_POST[$para];
		}else{
			return $return;
		}
	}

	public static function string2array($tags)
	{
		return preg_split('/ /',trim($tags),-1);
	}

	public static function array2string($tags)
	{
		return implode(' ',$tags);
	}

	public static function delhtml($html){
		$html = strip_tags(htmlspecialchars_decode($html));
		return $html;

	}
	/**
	 * 返回当前日期
	 * 
	 * @param $hour mixed
	 * @return bool
	 */
	public static function now($hour = true){
		return $hour ? date('Y-m-d H:i:s') : date('Y-m-d');
	}
	

	/**
	 * 判断数组是否包含所有给定的键值
	 *  *
	 * @param $keys array
	 * @param $array array
	 * @return bool
	 */
	public static function array_keys_exist($keys,$array) {
	    return (count (array_intersect($keys,array_keys($array))) == count($keys));
	}
	
	/**
	 * div_info
	 *
	 * @param mixed $flag
	 * @param mixed $info
	 * @param mixed $database
	 * @param mixed $argu1
	 * @param mixed $argu2
	 * @return void
	 */
	public static function json($flag = null, $info = null,$database = null,$id = null,$argu1=null,$argu2=null,$url=''){
			$result['flag']         = $flag;
			$result['info'] 		= $info;
			$result['data']			= $database;	
			$result['id']			= $id;
			$result['a1']			= $argu1;	
			$result['a2']			= $argu2;
			$r = isset($_SERVER['HTTP_X_REQUESTED_WITH']) ? strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) : '';
			$inAjax = $r == 'xmlhttprequest';
			if($inAjax){
				exit(json_encode( $result ));
			}else{
				header("Location:$url");exit;
			}
	}
	


	public static function getmicrotime(){
		list($usec,$sec) = explode(" ",microtime());
		return ((float)$usec + (float)$sec);
	}

public static function d_rand(){
	srand ((float) microtime() * 10000000);

}




//时间格式化
public static function sgmdate($dateformat, $timestamp='', $format=0) {
	$mtime = explode(' ', microtime());
	$_SGLOBAL['timestamp'] = $mtime[1];
	$_SGLOBAL['supe_starttime'] = $_SGLOBAL['timestamp'] + $mtime[0];
	//print_r($_SGLOBAL['supe_starttime']);exit;
	if(empty($timestamp)) {
		$timestamp = $_SGLOBAL['timestamp'];
	}
	$timeoffset = 8;
	$result = '';
	if($format) {
		$time = $_SGLOBAL['timestamp'] - $timestamp;
		if($time > 24*3600) {
			$result = gmdate($dateformat, $timestamp + $timeoffset * 3600);
		} elseif ($time > 3600) {
			$result = intval($time/3600).lang('hour').lang('before');
		} elseif ($time > 60) {
			$result = intval($time/60).lang('minute').lang('before');
		} elseif ($time > 0) {
			$result = $time.lang('second').lang('before');
		} else {
			$result = lang('now');
		}
	} else {
		$result = gmdate($dateformat, $timestamp + $timeoffset * 3600);
	}
	return $result;
}


/**
*计算time_stamp 时间差*
*@param int $timestamp;
*@return void
*/
public static function datediff($timestamp){
	$measure = array('秒前','分钟前','小时前','天前','月前','年前');
	$i = 0;
	$now =  time();
	$mod =$now-strtotime($timestamp);
	$flag = 60;
	while($mod >= $flag && $i <=5){
		switch($i){
			case '2':
			$mod = $mod >= 24 ? Floor($mod/24) : $mod;
			$flag = 30;
			break;
			case '3':
			$mod = $mod >= 30 ? Floor($mod/30) : $mod;
			break;
			case '1':
			$mod = Floor($mod/60);
			$flag = 24;
			break;
			default :
			$mod = Floor($mod/60);
			break;
		}
		$i++;
	}
	return $mod.$measure[$i];
}

public static function to_time($time){
   $now_time = time(); 
   $diff = $now_time - $time;
   if($diff < 0){
    return $time; 
   }else{
		if($diff < 60){
			return $diff.'秒前'; 
		}else{
			if($diff < 3600){
				return floor($diff/60).'分钟前'; 
			}else{
				if($diff < 86400){
					return floor($diff/3600).'小时前'; 
				}else{
					if($diff < 259200){//3天内
						return floor($diff/86400).'天前';
					}else{
						return date('m月d日 H:i',$time);
					}
				}
			}
		}
   }
}

public static function time_cut($date,$year = true){//$year是否显示年份，默认为显示
	if(!$date) return date('Y-m-d');
	$day = strtotime("today");
	$date = strtotime($date);
	$dates = strtotime(date('Y-m-d',$date));
	$diff = $day-$dates;

		if($diff<86400){
			return date('H:i',$date);
		}else{
			if($year){
				return date('Y-m-d',$date);
			}else{
				return date('m-d',$date);
			}
		}
}

// 字符串截取
public static function ncSubstr( $str, $len = 0, $dot = false, $encoding = 'utf-8' ) {
        $str = strip_tags( htmlspecialchars_decode($str) );
        $str = str_ireplace(array('&amp;', '&quot;', '&lt;', '&gt;','&nbsp;'), array(), $str);
		$str = trim($str);
		$strlen = strlen($str);
        if ( !$len || $strlen <= $len ) return $str;
        if ($encoding == 'utf-8') {
			$tmpStr = $str;
			$nowStr = '';
                $start = 0;
                while($start < $len) {
                        $t = ord($str[$start]);
						//dbg($str[4],true);dbg($t,true);dbg(chr($t),true);$ssss .= substr($str,4,3);dbg($ssss);
                        if($t == 9 || $t == 10 || (32 < $t && $t <= 126)) {
								$nowStr .= substr($tmpStr,0,1);
                                 $start++;
								$tmpStr = substr($str,$start,$strlen);
                        } elseif (194 <= $t && $t <= 253) {
								$nowStr .= substr($tmpStr,0,3);
                                $start += 3;
								$tmpStr = substr($str,$start,$strlen);
                        } else {
							$start++;
							$tmpStr = substr($str,$start,$strlen);
                        } 
                }
				if($strlen > $len){
					return $nowStr.$dot;
				}else{
					return $nowStr;
				}
        } elseif ($encoding == 'gbk') {
                for ($i=0; $i<$len; $i++) {
                        $nowStr .= ord($str{$i}) > 127 ? $str{$i}.$str{++$i} : $str{$i};
                }
        }
        $nowStr = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $nowStr);
        return $nowStr.$dot;
}


	public static function splitword($subject,$content){
		$subjectenc = rawurlencode(strip_tags($subject));
		$messageenc = rawurlencode(strip_tags(preg_replace("/\[.+?\]/U", '', $content)));
		$data = @implode('', file("http://keyword.discuz.com/related_kw.html?title=$subjectenc&content=$messageenc&ics=utf-8&ocs=utf-8"));
		$kws = array();
		if($data) {
			$parser = xml_parser_create();
			xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
			xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
			xml_parse_into_struct($parser, $data, $values, $index);
			xml_parser_free($parser);
			foreach($values as $valuearray) {
				if($valuearray['tag'] == 'kw' || $valuearray['tag'] == 'ekw') {
						$kws[] = trim($valuearray['value']);
				}
			}			
		}
		return $kws;
	}

}